/**
 * 
 */
package cn.dgfy.MyBatisStudy.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @author Tearfalls
 *
 */
public class DbUtil {
	
	private static SqlSessionFactory factory = null;
	
	private static SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}
	
	private static SqlSession getSqlSession(boolean autoCommit) throws IOException {
		if (factory == null) {
			factory = getSqlSessionFactory();
		}
		
		return factory.openSession(autoCommit);
	}
	
	public static SqlSession getNonAutoCommitSqlSession() throws IOException {
		return getSqlSession(false);
	}
	
	public static SqlSession getAutoCommitSqlSession() throws IOException {
		return getSqlSession(true);
	}
}
